#include "Rule.h"
#include <exception/NpException.h>

using namespace std;
using namespace ruleconfiguration;
using namespace npexception;

static const char g_ruleDir[] = "/RuleConfigInfo";

Rule::Rule() : XmlConfBase("")
{
  reset();
}

Rule::Rule(const string& fileName) : XmlConfBase(fileName)
{
  initializeConfigs();
}

Rule::~Rule()
{
  reset();
}

void Rule::reset()
{
  if (m_toBeDestroy == true)
  {
    destoryRulConfigInfo(m_rule);
  }
  m_toBeDestroy = true;
}

void Rule::todo(const pugi::xml_document &pugixml)
{
  reset();
  const pugi::xpath_node* firstNode = getFirstNode(g_ruleDir, pugixml);
  for (pugi::xml_node::iterator it = firstNode->node().begin(); it != firstNode->node().end(); ++it)
  {
    static string regexName;
    regexName = (*it).child_value("RegexName");

    RegexInfo* regexinfo = new RegexInfo();
    m_rule[regexName] = regexinfo;

    fillInfo(*it, *m_rule[regexName]);
  }
}

void Rule::fillInfo(const pugi::xml_node& node, ruleconfiguration::RegexInfo &regexInfo)
{
  regexInfo.Pattern = node.child_value("Pattern");
  regexInfo.Method = node.child_value("Method");
  regexInfo.FilterPattern = node.child_value("FilterPattern");
  string options(node.child_value("Options"));
  if(options == "match_single_line")
  {
    regexInfo.Options= boost::regex_constants::match_single_line;
  }
  else if(options == "match_not_dot_newline")
  {
    regexInfo.Options= boost::regex_constants::match_not_dot_newline;
  }
  else
  {
    regexInfo.Options = boost::regex_constants::match_default;
  }
}

RegexInfo* Rule::getRegex(const string& RegexName)
{
  RuleConfigInfoIterator it = m_rule.find(RegexName);
  throwExIf(it == m_rule.end(), INVALID_REGEX_NAME);
  return it->second;
}
